#region Summary

// 
// Owner : JackieHan 
// 
// Solution : DailyCollection 
// 
// Project : Jackie.Utility.Notify
// 
// File : MessageCollection.cs
// 
// CopyRight : Copyright © 2010-2011 Skomart Corporation, All Rights Reserved 
// 
// Summary : 消息集合
// 
// History : 
//			2011-04-26 14:40:49	    Create 
// 

#endregion

#region Using

using System;
using System.Collections.Generic;
using System.Linq;
using Jackie.Utility.CustomExtension;

#endregion

namespace Jackie.Utility.Notify.Domain
{
    //public delegate void MessageArrivedHandler(object sender, MessageArrivedEventArgs e);

    //public class MessageArrivedEventArgs : EventArgs
    //{
    //    /// <summary>
    //    /// 消息
    //    /// </summary>
    //    public MessageInfo Message { get; set; }
    //}

    /// <summary> 
    /// 消息集合
    /// </summary>
    public class TitleMessageCollection
    {
        private static TitleMessageCollection instance;
        private static readonly object LockObject = new object();

        public static TitleMessageCollection GetInstance()
        {
            if (instance == null)
            {
                lock (LockObject)
                {
                    if (instance == null)
                        instance = new TitleMessageCollection();
                }
            }
            return instance;
        }

        private TitleMessageCollection()
        {
            titleMessages = new Dictionary<string, IList<MessageInfo>>();
        }

        private IDictionary<string, IList<MessageInfo>> titleMessages;

        //public event MessageArrivedHandler MessageArrived;

        public void Add(MessageInfo info)
        {
            if (!TitleCollection.GetInstance().Contains(info.Title))
                throw new Exception("没有相关消息标题!");

            if (titleMessages.ContainsKey(info.Title.Code))
            {
                var messages = titleMessages[info.Title.Code];
                messages.Add(info);
            }
            else
            {
                if (TitleCollection.GetInstance().Contains(info.Title))
                {
                    var messages = new List<MessageInfo> { info };
                    titleMessages.Add(info.Title.Code, messages);
                }
            }

            var clients = ClientSubscribeCollection.GetInstance().GetClients(info.Title.Code);
            clients.ForEach(item => item.CallbackInstance.Process(info));
        }

    }
}